<template>
  <div class="option-items-pane">
    <el-radio-group
      v-if="
        selectedWidget.type === 'radio' ||
        (selectedWidget.type === 'select' && !selectedWidget.options.multiple)
      "
      v-model="optionModel.defaultValue"
      @change="emitDefaultValueChange"
    >
      <draggable
        tag="ul"
        :list="optionModel.optionItems"
        item-key="id"
        v-bind="{ group: 'optionsGroup', ghostClass: 'ghost', handle: '.drag-option' }"
      >
        <template #item="{ element: option, index: idx }">
          <li>
            <el-radio :label="option.value" :value="option.value">
              <el-input v-model="option.value" size="small" style="width: 100px"></el-input>
              <el-input v-model="option.label" size="small" style="width: 100px"></el-input>
              <i class="iconfont icon-drag drag-option"></i>
              <el-button
                circle
                plain
                size="small"
                type="danger"
                @click="deleteOption(option, idx)"
                icon="el-icon-minus"
                class="col-delete-button"
              ></el-button>
              <el-button
                size="small"
                type="primary"
                circle
                v-if="selectedWidget.type === 'radio'"
                @click="confirmLogic(option, idx)"
                class="col-delete-button"
                icon="el-icon-pointer"
              ></el-button>
            </el-radio>
          </li>
        </template>
      </draggable>
    </el-radio-group>
    <el-checkbox-group
      v-else-if="
        selectedWidget.type === 'checkbox' ||
        (selectedWidget.type === 'select' && selectedWidget.options.multiple)
      "
      v-model="optionModel.defaultValue"
      @change="emitDefaultValueChange"
    >
      <draggable
        tag="ul"
        :list="optionModel.optionItems"
        item-key="id"
        v-bind="{ group: 'optionsGroup', ghostClass: 'ghost', handle: '.drag-option' }"
      >
        <template #item="{ element: option, index: idx }">
          <li>
            <el-checkbox :label="option.value" :value="option.value">
              <el-input v-model="option.value" size="small" style="width: 100px"></el-input>
              <el-input v-model="option.label" size="small" style="width: 100px"></el-input>
              <i class="iconfont icon-drag drag-option"></i>
              <el-button
                circle
                plain
                size="small"
                type="danger"
                @click="deleteOption(option, idx)"
                icon="el-icon-minus"
                class="col-delete-button"
              ></el-button>
            </el-checkbox>
          </li>
        </template>
      </draggable>
    </el-checkbox-group>
    <div v-else-if="selectedWidget.type === 'cascader'" class="full-width-input">
      <el-cascader
        v-model="optionModel.defaultValue"
        :options="optionModel.optionItems"
        @change="emitDefaultValueChange"
        :placeholder="i18nt('render.hint.selectPlaceholder')"
      >
      </el-cascader>
    </div>
    <div v-if="selectedWidget.type === 'cascader'">
      <el-button link type="primary" @click="importCascaderOptions">{{
        i18nt('designer.setting.importOptions')
      }}</el-button>
      <el-button link type="primary" @click="resetDefault">{{
        i18nt('designer.setting.resetDefault')
      }}</el-button>
    </div>

    <div
      v-if="
        selectedWidget.type === 'radio' ||
        selectedWidget.type === 'checkbox' ||
        selectedWidget.type === 'select'
      "
    >
      <el-button link type="primary" @click="addOption">{{
        i18nt('designer.setting.addOption')
      }}</el-button>
      <el-button link type="primary" @click="importOptions">{{
        i18nt('designer.setting.importOptions')
      }}</el-button>
      <el-button link type="primary" @click="resetDefault">{{
        i18nt('designer.setting.resetDefault')
      }}</el-button>
    </div>

    <div
      v-if="showImportDialogFlag"
      class=""
      v-drag="['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header']"
    >
      <el-dialog
        :title="i18nt('designer.setting.importOptions')"
        v-model="showImportDialogFlag"
        :show-close="true"
        class="drag-dialog small-padding-dialog"
        append-to-body
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :destroy-on-close="true"
      >
        <el-form-item>
          <el-input type="textarea" rows="10" v-model="optionLines"></el-input>
        </el-form-item>
        <template #footer>
          <div class="dialog-footer">
            <el-button size="large" type="primary" @click="saveOptions">{{
              i18nt('designer.hint.confirm')
            }}</el-button>
            <el-button size="large" @click="showImportDialogFlag = false">{{
              i18nt('designer.hint.cancel')
            }}</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <div
      v-if="showImportCascaderDialogFlag"
      class=""
      v-drag="['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header']"
    >
      <el-dialog
        :title="i18nt('designer.setting.importOptions')"
        v-model="showImportCascaderDialogFlag"
        :show-close="true"
        class="drag-dialog small-padding-dialog"
        append-to-body
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :destroy-on-close="true"
      >
        <code-editor v-model="cascaderOptions" mode="json" :readonly="false"></code-editor>
        <template #footer>
          <div class="dialog-footer">
            <el-button size="large" type="primary" @click="saveCascaderOptions">{{
              i18nt('designer.hint.confirm')
            }}</el-button>
            <el-button size="large" @click="showImportCascaderDialogFlag = false">{{
              i18nt('designer.hint.cancel')
            }}</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div
      v-if="showLogicFlag"
      class=""
      v-drag="['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header']"
    >
      <el-dialog
        :title="i18nt('designer.setting.confirmLogic')"
        v-model="showLogicFlag"
        v-drag="['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header']"
        :show-close="true"
        class="drag-dialog small-padding-dialog"
        append-to-body
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :destroy-on-close="true"
      >
        <div>
          <el-radio-group v-model="logicRadio">
            <el-radio :value="1" size="large">显 示</el-radio>
            <el-radio :value="0" size="large">隐 藏</el-radio>
          </el-radio-group>
          <!-- <p>选择题组</p> -->
          <p>
            <el-button type="primary" @click="handleSelectComponent" size="default"
              >选择题组</el-button
            >
          </p>

          <!-- <el-select
            v-model="showList"
            multiple
            @change="changeLogicShow"
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="2"
            placeholder="请选择题组"
            style="width: 320px"
            size="default"
            v-if="logicRadio == 1"
          >
            <el-option
              v-for="item in optionsLogic"
              :key="item"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-model="hideList"
            multiple
            @change="changeLogicHide"
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="2"
            placeholder="请选择题组"
            style="width: 320px"
            size="default"
            v-if="logicRadio == 0"
          >
            <el-option
              v-for="item in optionsLogic"
              :key="item"
              :label="item.label"
              :value="item.id"
            />
          </el-select> -->
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button size="large" type="primary" @click="saveLogicOptions">{{
              i18nt('designer.hint.confirm')
            }}</el-button>
            <el-button size="large" @click="showLogicFlag = false">{{
              i18nt('designer.hint.cancel')
            }}</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <el-dialog
      title="选择题组"
      v-model="selectComponentDialog"
      v-drag="['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header']"
      :show-close="true"
      class="drag-dialog small-padding-dialog select-component-dialog"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      width="80%"
      @close="closeSelectComponent"
      top="5vh"
    >
      <VFormRender ref="vFormRef" :form-json="formJson"> </VFormRender>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" type="primary" @click="confirmSelectComponentDialog">{{
            i18nt('designer.hint.confirm')
          }}</el-button>
          <el-button size="large" @click="selectComponentDialog = false">{{
            i18nt('designer.hint.cancel')
          }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { change } from '@/api/job/jobinfo';
import CodeEditor from '@/components/code-editor-formdesigner/index';
import i18n from '@/utils/i18n';
import VFormRender from '@/components/form-render/index';
import { deepClone } from '@/utils/util';
export default {
  name: 'OptionItemsSetting',
  mixins: [i18n],
  components: {
    CodeEditor,
    VFormRender,
  },
  props: {
    designer: Object,
    selectedWidget: Object,
  },
  data() {
    return {
      showImportDialogFlag: false,
      optionLines: '',
      formJson: {},
      cascaderOptions: '',
      showImportCascaderDialogFlag: false,
      showLogicFlag: false,

      //separator: '||',
      separator: ',',
      optionsLogic: [],
      selectComponent: [],
      logicRadio: 0,
      currentIndex: -1,
      showList: [],
      hideList: [],
      showArr: [],
      hideArr: [],
      selectComponentDialog: false,
      option: {},
    };
  },
  computed: {
    optionModel() {
      return this.selectedWidget.options;
    },
  },
  watch: {
    'selectedWidget.options': {
      deep: true,
      handler(val) {
        //console.log('888888', 'Options change!')
      },
    },
  },
  methods: {
    handleSelectComponent() {
      let checkedList = [];

      if (!!this.option.logic) {
        if (this.logicRadio == 1) {
          checkedList = this.option.logic.filter(item => item.show).map(item => item.componentId);
        } else if (this.logicRadio == 0) {
          checkedList = this.option.logic.filter(item => !item.show).map(item => item.componentId);
        }
      }

      console.log('checkedList', checkedList, this.option);

      this.$store.commit('SET_CHECKED_LIST', checkedList);
      localStorage.removeItem('checkedList');
      this.selectComponentDialog = true;
      this.$store.commit('SET_SELECT_COMPONENT_DIALOG', this.selectComponentDialog);
    },
    closeSelectComponent() {
      this.selectComponentDialog = false;

      this.$store.commit('SET_SELECT_COMPONENT_DIALOG', this.selectComponentDialog);
    },
    confirmSelectComponentDialog() {
      this.optionModel.optionItems[this.currentIndex].logic = [];
      // this.selectComponent = []
      // this.showArr = []
      // this.hideArr = []
      if (this.logicRadio == 1) {
        this.showList = JSON.parse(localStorage.getItem('checkedList'));
        console.log('this.showList', this.showList);

        this.showList.forEach(item => {
          this.showArr.push({
            componentId: item,
            show: true,
          });
        });
      } else if (this.logicRadio == 0) {
        this.hideList = JSON.parse(localStorage.getItem('checkedList'));
        console.log('this.hideList', this.hideList);

        this.hideList.forEach(item => {
          this.hideArr.push({
            componentId: item,
            show: false,
          });
        });
      }
      this.selectComponentDialog = false;
    },
    emitDefaultValueChange() {
      if (!!this.designer && !!this.designer.formWidget) {
        let fieldWidget = this.designer.formWidget.getWidgetRef(this.selectedWidget.options.name);
        if (!!fieldWidget && !!fieldWidget.refreshDefaultValue) {
          fieldWidget.refreshDefaultValue();
        }
      }
    },

    deleteOption(option, index) {
      this.optionModel.optionItems.splice(index, 1);
    },
    confirmLogic(option, index) {
      console.log('option', option);
      this.option = option;
      this.logicRadio = 1;
      this.hideList = [];
      this.showList = [];
      this.selectComponent = [];
      this.showArr = [];
      this.hideArr = [];

      if (!!option.logic) {
        option.logic.forEach(item => {
          item.show ? this.showList.push(item.componentId) : this.hideList.push(item.componentId);
        });
      }

      this.currentIndex = index;

      //   console.log(this.designer, '222');
      this.optionsLogic = this.collectWidgetIds(this.designer.widgetList);
      let widgetList = deepClone(this.designer.widgetList);
      let formConfig = deepClone(this.designer.formConfig);
      this.formJson = JSON.parse(JSON.stringify({ widgetList, formConfig }, null, '  '));

      this.showLogicFlag = true;
      if (!option.logic) {
        return '';
      }

      option.logic.forEach(item => {
        item.show ? (this.logicRadio = 1) : (this.logicRadio = 0);
        this.selectComponent.push(item.componentId);
      });
    },
    collectWidgetIds(data) {
      const result = [];

      function traverse(obj) {
        if (!obj || typeof obj !== 'object') return;

        // 处理当前对象的ID
        if (obj.id !== undefined && !obj.id.includes('grid') && !obj.id.includes('table')) {
          result.push({
            id: obj.id,
            label: obj.id + '_' + obj.options.label,
          });
        }

        // 递归处理所有属性
        for (const key in obj) {
          if (typeof obj[key] === 'object') {
            traverse(obj[key]); // 递归处理对象/数组
          }
        }
      }

      // 从根节点开始遍历
      data.forEach(item => traverse(item));
      return [...new Set(result)]; // 去重后返回
    },
    /*     changeLogicShow(val) {
      console.log('val', val);
      this.showArr = [];
      this.optionModel.optionItems[this.currentIndex].logic = [];
      val.forEach(item => {
        this.showArr.push({
          componentId: item,
          show: true,
        });
      });
    },
    changeLogicHide(val) {
      this.hideArr = [];
      this.optionModel.optionItems[this.currentIndex].logic = [];
      val.forEach(item => {
        this.hideArr.push({
          componentId: item,
          show: false,
        });
      });
    }, */
    saveLogicOptions() {
      this.selectComponent = this.showArr.concat(this.hideArr);
      console.log('this.selectComponent', this.selectComponent);

      if (this.selectComponent.length > 0) {
        this.optionModel.optionItems[this.currentIndex].logic = this.selectComponent;

        console.log('this.optionModel.optionItems', this.optionModel.optionItems);
        // return;
        const eventHandlerCode = this.generateLogicCode(this.optionModel.optionItems);

        this.optionModel.onChange = eventHandlerCode;
        this.showLogicFlag = false;
      }
    },
    generateLogicCode(conditions) {
      return conditions
        .map((condition, index) => {
          // 生成条件判断语句
          const conditionClause = `${index === 0 ? 'if' : 'else if'} (value == ${
            condition.value
          }) {`;

          // 生成组件操作代码
          console.log('condition.logic', condition);
          if (!condition.logic) {
            return '';
          }
          const actionLines = condition.logic
            .map(logic => {
              const action = logic && logic.show ? 'showWidgets' : 'hideWidgets';
              return `this.getFormRef().${action}("${logic.componentId}")`;
            })
            .join('\n  ');

          //   组合代码块
          return `${conditionClause}
  ${actionLines}
}`;
        })
        .join('\n');
    },

    addOption() {
      let newValue = this.optionModel.optionItems.length + 1;
      this.optionModel.optionItems.push({
        value: newValue,
        label: 'new option',
      });
    },

    importOptions() {
      this.optionLines = '';
      if (this.optionModel.optionItems.length > 0) {
        this.optionModel.optionItems.forEach(opt => {
          if (opt.value === opt.label) {
            this.optionLines += opt.value + '\n';
          } else {
            this.optionLines += opt.value + this.separator + opt.label + '\n';
          }
        });
      }

      this.showImportDialogFlag = true;
    },

    saveOptions() {
      let lineArray = this.optionLines.split('\n');
      //console.log('test', lineArray)
      if (lineArray.length > 0) {
        this.optionModel.optionItems = [];
        lineArray.forEach(optLine => {
          if (!!optLine && !!optLine.trim()) {
            if (optLine.indexOf(this.separator) !== -1) {
              this.optionModel.optionItems.push({
                value: optLine.split(this.separator)[0],
                label: optLine.split(this.separator)[1],
              });
            } else {
              this.optionModel.optionItems.push({
                value: optLine,
                label: optLine,
              });
            }
          }
        });
      } else {
        this.optionModel.optionItems = [];
      }

      this.showImportDialogFlag = false;
    },

    resetDefault() {
      if (
        this.selectedWidget.type === 'checkbox' ||
        (this.selectedWidget.type === 'select' && this.selectedWidget.options.multiple)
      ) {
        this.optionModel.defaultValue = [];
      } else {
        this.optionModel.defaultValue = '';
      }

      this.emitDefaultValueChange();
    },

    importCascaderOptions() {
      this.cascaderOptions = JSON.stringify(this.optionModel.optionItems, null, '  ');
      this.showImportCascaderDialogFlag = true;
    },

    saveCascaderOptions() {
      try {
        let newOptions = JSON.parse(this.cascaderOptions);
        this.optionModel.optionItems = newOptions;
        //TODO: 是否需要重置选项默认值？？

        this.showImportCascaderDialogFlag = false;
      } catch (ex) {
        this.$message.error(this.i18nt('designer.hint.invalidOptionsData') + ex.message);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.option-items-pane {
  width: 100%;

  ul {
    padding-inline-start: 6px;
    padding-left: 6px; /* 重置IE11默认样式 */
  }
}

li.ghost {
  background: #fff;
  border: 2px dotted $color_primary;
}

.drag-option {
  cursor: move;
  margin: 5px;
}

.small-padding-dialog :deep(.el-dialog__body) {
  padding: 10px 15px;
}

.dialog-footer .el-button {
  width: 100px;
}

.full-width-input {
  width: 100% !important;

  :deep(.el-cascader) {
    width: 100% !important;
  }
}
</style>
<style lang="scss">
.select-component-dialog {
  .el-dialog__body {
    max-height: 75vh !important;
    overflow-y: auto;
  }
}
</style>
